package com.googlecode.cswish.struts;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

import com.googlecode.cswish.struts.conversion.PageConverter;
import com.googlecode.cswish.struts.spring.ObjectFactory;
import com.opensymphony.module.sitemesh.Config;
import com.opensymphony.module.sitemesh.Decorator;
import com.opensymphony.module.sitemesh.DecoratorMapper;
import com.opensymphony.module.sitemesh.Page;
import com.opensymphony.module.sitemesh.mapper.AbstractDecoratorMapper;
import com.opensymphony.module.sitemesh.mapper.DefaultDecorator;

public class SiteMeshLayoutDecoratorMapper extends AbstractDecoratorMapper {
	/**
	 * use LayoutDecorator if parameter layoutName is found
	 */
    private String layoutName;
    
    /**
     * don't decorate them if these parameter and resultCodes are found
     */
    private String excludeParam;
    private Map<String, String> excludeResults;

    private PageConverter pageConverter;
    
    public void init(Config config, Properties properties, DecoratorMapper parent) throws InstantiationException {
        super.init(config, properties, parent);
        
        layoutName  = properties.getProperty("layout.name", "layout");
        excludeParam = properties.getProperty("excludeParam");
        String exclude = properties.getProperty("excludeValues");
        if (exclude != null && excludeParam != null) {
        	excludeResults = new HashMap<String, String>();
        	String[] excludes = StringUtils.split(exclude, ',');
        	for (String s : excludes) {
        		excludeResults.put(s, s);
        	}
        }
        
        pageConverter = ObjectFactory.getInstance().getBean(PageConverter.class, true);
    }

    public Decorator getDecorator(HttpServletRequest request, Page page) {
    	if (excludeResults != null) {
    		String resultCode = request.getParameter(excludeParam);
    		if (resultCode != null && excludeResults.get(resultCode) != null) {
    			return null;
    		}
    	}
    	
    	String layout = request.getParameter(this.layoutName);
    	if (layout == null) {
    		layout = (String) request.getAttribute(this.layoutName);
    	}
    	Decorator decorator;
        if (layout != null) {
        	decorator = getNamedDecorator(request, layout);
        } else {
        	String thisPath =  Routing.getUri(request);
        	String templatePath = pageConverter.getPageTemplate(thisPath);
        	if (templatePath != null) {
        		decorator = new DefaultDecorator(thisPath, templatePath, Collections.EMPTY_MAP);
        	} else {
        		decorator = null;
        	}
        }
        return decorator;
    }
}